package com.webrtc.demo.contacts

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.webrtc.demo.R
import com.webrtc.demo.contacts.adapter.ContactsSelectListAdapter
import com.webrtc.demo.util.ContactsUtils
import kotlinx.android.synthetic.main.activity_contacts_select_list.*

class ContactsSelectListActivity : AppCompatActivity(), OnItemChildClickListener {

    companion object {

        const val EXTRA_DATA = "extra_data"

        fun launch(activity: Activity, requestCode: Int) {
            activity.startActivityForResult(
                Intent(activity, ContactsSelectListActivity::class.java),
                requestCode
            )
        }
    }

    private val adapter: ContactsSelectListAdapter by lazy { ContactsSelectListAdapter() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_contacts_select_list)

        title = "选择成员"

        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
        recyclerView.adapter = adapter

        loadData()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        val inflater = menuInflater
        inflater.inflate(R.menu.add_contacts_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.confirm -> {
                val selectedUidList = adapter.getSelectedUidList()
                if (selectedUidList.isEmpty()) {
                    Toast.makeText(this, "请选择成员", Toast.LENGTH_SHORT).show()
                } else {
                    val data = Intent().apply {
                        putStringArrayListExtra(EXTRA_DATA, ArrayList(selectedUidList))
                    }
                    setResult(Activity.RESULT_OK, data)
                    finish()
                }
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun loadData() {
        val contactsList = ContactsUtils.getContactsList(this)
        adapter.setNewData(contactsList)
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {

    }
}